package net.code.btalk.ui;

import java.util.Vector;

import com.hoodemia.ui.StandardButton;
import com.hoodemia.ui.StandardTextField;
import com.hoodemia.ui.SuperDuperFieldManager;

import net.code.btalk.BTalk;
import net.code.btalk.BTalkResource;
import net.code.btalk.Buddy;
import net.code.btalk.UpdateChecker;
import net.rim.blackberry.api.messagelist.ApplicationIcon;
import net.rim.blackberry.api.messagelist.ApplicationIndicator;
import net.rim.blackberry.api.messagelist.ApplicationIndicatorRegistry;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.DialogClosedListener;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.image.ImageFactory;
import net.rim.device.api.util.StringProvider;

public class BuddyScreen extends MainScreen {
	public static BTalk btalk;
	public IconLabelField statusBanner;
	public BuddyListField buddyList;
	public StandardTextField searchBar;
	public Vector allFriends;
	protected StandardButton searchButton;
	protected ButtonField showAllButton;

	public BuddyScreen(BuddyListField list) {
		statusBanner = new IconLabelField(BuddyListField.onlineIconSmall,
				BTalkLocale.getString(BTalkResource.BUDDY_SCREEN_STATUS_AVAILABLE)) {
			protected void layout(int width, int height) {
				// TODO Auto-generated method stub
				super.layout(width, 30);
				setExtent(width, 30);
			}
		};
		this.setTitle(statusBanner);

		SuperDuperFieldManager searchSection = new SuperDuperFieldManager(SuperDuperFieldManager.JUSTIFY_LEFT_AND_RIGHT);
		int spaces = Display.getWidth() / 8;
		searchSection.setPadding(0, spaces, 0, spaces);

		// search field
		searchBar = new StandardTextField("search friends", 100, StandardTextField.FIELD_HCENTER & StandardTextField.NO_NEWLINE);
		searchBar.setPadding(6, 2, 7, 5);

		// search button
		searchButton = new StandardButton("", StandardButton.FIELD_HCENTER, StandardButton.PADDING_SMALL);
		searchButton.setImage(ImageFactory.createImage(Bitmap
				.getBitmapResource("img/search.png")));

		// button for showing all friends - not yet implemented
		showAllButton = new ButtonField("Show All Friends", Field.FIELD_HCENTER) {

			public int getPreferredHeight() {
				return 40;
			}

			protected void layout(int width, int height) {
				super.layout(this.getPreferredWidth(), 40);
				super.setExtent(this.getPreferredWidth(), 40);
				this.setExtent(this.getPreferredWidth(), 40);
			}

		};
		showAllButton.setFont(Constants.FONT_BOLD_STYLE);
		showAllButton.setPadding(Constants.BUTTON_PADDING);

		showAllButton.setBorder(ButtonField.VISUAL_STATE_NORMAL,
				Constants.SIMPLE_GRAY_BORDER, true);
		showAllButton.setBorder(ButtonField.VISUAL_STATE_FOCUS,
				Constants.SIMPLE_ORANGE_BORDER, true);
		showAllButton.setBorder(ButtonField.VISUAL_STATE_ACTIVE,
				Constants.SIMPLE_ORANGE_BORDER, true);

		showAllButton.setBackground(ButtonField.VISUAL_STATE_NORMAL,
				Constants.BUTTON_BACKGROUND_GREY_GRADIENT);
		showAllButton.setBackground(ButtonField.VISUAL_STATE_FOCUS,
				Constants.BUTTON_BACKGROUND_BLUE_GRADIENT);

		FieldChangeListener searchButtonListener = new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				/*Vector temp = new Vector();
				int counter = 0;
				while (counter < allFriends.size()) {
					Buddy d = (Buddy) (allFriends.elementAt(counter));
					if (d.name.indexOf(searchBar.getText().toString()) > -1) {
						temp.addElement(d);
					}
					counter++;
				}
				buddyList.replaceBuddies(temp);*/
				btalk.sendFixedMessage();
			}
		};

		FieldChangeListener showAllButtonListener = new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				buddyList.replaceBuddies(allFriends);
			}
		};

		searchButton.setChangeListener(searchButtonListener);
		showAllButton.setChangeListener(showAllButtonListener);

		searchSection.add(searchBar);
		searchSection.add(searchButton);

		this.add(searchSection);

		this.buddyList = list;
		allFriends = list.buddyVector;
		this.add(list);

		this.addMenuItem(new MenuItem(new StringProvider(BTalkLocale
				.getString(BTalkResource.BUDDY_SCREEN_MI_CHAT)), 0, 0) {
			public void run() {
				int idx = buddyList.getSelectedIndex();
				if (idx >= 0) {
					btalk.currentBuddy = (Buddy) buddyList.buddyVector
							.elementAt(idx);
					btalk.openBuddy(btalk.currentBuddy);
				}
			}
		});

		this.addMenuItem(new MenuItem(new StringProvider(BTalkLocale
				.getString(BTalkResource.BUDDY_SCREEN_MI_RETRY)), 1, 0) {
			public void run() {
				if (btalk.state == BTalk.STATE_FAILED) {
					btalk.state = BTalk.STATE_RETRYING;
					btalk.setMyStatus(BTalk.STATE_RETRYING, false, null);
					btalk.retryCount = 0;
					btalk.retryBtalk();
				}
			}
		});
		
		this.addMenuItem(new MenuItem(new StringProvider("Register indicator"), 2, 0) {
			public void run() {
				EncodedImage appIconEncoded = EncodedImage.getEncodedImageResource("icon/app_logo_shine_notified_64.png");
				ApplicationIcon appIcon = new ApplicationIcon(appIconEncoded);

				try {
					ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
					ApplicationIndicator indicator = reg.register(appIcon, ApplicationIndicator.RIGHT, false);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		
		this.addMenuItem(new MenuItem(new StringProvider("Unregister indicator"), 3, 0) {
			public void run() {
				try {
		    		ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
		    				.getInstance();
		    		reg.unregister();
		    	} catch (Exception e) {
		    		e.printStackTrace();
		    	}
			}
		});

		this.addMenuItem(new MenuItem(new StringProvider(BTalkLocale
				.getString(BTalkResource.BUDDY_SCREEN_MI_BUDDY_INFO)),
				0x00020010, 0) {
			// NOTICE: this array use status as index
			// final String[] STATUS_STR = new String[]
			// {BTalkLocale.locale[BTalkLocale.ITEM_BUDDY_OFFLINE][SavedData.lang],
			// BTalkLocale.locale[BTalkLocale.ITEM_BUDDY_AWAY][SavedData.lang],
			// BTalkLocale.locale[BTalkLocale.ITEM_BUDDY_BUSY][SavedData.lang],
			// BTalkLocale.locale[BTalkLocale.ITEM_BUDDY_ONLINE][SavedData.lang]};
			final String[] STATUS_STR = new String[] {
					BTalkLocale
							.getString(BTalkResource.BUDDY_SCREEN_POP_INFO_OFFLINE),
					BTalkLocale
							.getString(BTalkResource.BUDDY_SCREEN_POP_INFO_AWAY),
					BTalkLocale
							.getString(BTalkResource.BUDDY_SCREEN_POP_INFO_BUSY),
					BTalkLocale
							.getString(BTalkResource.BUDDY_SCREEN_POP_INFO_AVA) };

			public void run() {
				if (buddyList.buddyVector.size() <= 0)
					return;
				Buddy b = buddyList.getBuddyAt(buddyList.getSelectedIndex());

				if (b == null)
					return;
				if (b.name.equalsIgnoreCase(b.jid)) {
					Dialog buddyInfoDialog = new Dialog(Dialog.D_OK, "ID: "
							+ b.jid + "\n" + STATUS_STR[b.status] + "\n"
							+ b.custom_str, 0, null, Screen.LEFTMOST);
					buddyInfoDialog.setEscapeEnabled(true);
					buddyInfoDialog.show();
				} else {
					Dialog buddyInfoDialog = new Dialog(Dialog.D_OK, "Name: "
							+ b.name + "\nID: " + b.jid + "\n"
							+ STATUS_STR[b.status] + "\n" + b.custom_str, 0,
							null, Screen.LEFTMOST);
					buddyInfoDialog.setEscapeEnabled(true);
					buddyInfoDialog.show();
				}
			}
		});

		this.addMenuItem(new MenuItem(new StringProvider(BTalkLocale
				.getString(BTalkResource.BUDDY_SCREEN_MI_NEW_BUDDY)),
				0x00020011, 0) {
			public void run() {
				// TODO finish add new buddy
				final EditField jidField;
				// Dialog addBuddyDialog = new Dialog(Dialog.D_OK_CANCEL,
				// BTalkLocale.locale[BTalkLocale.ITEM_ADD_LAB][SavedData.lang],
				// 0, null, Manager.USE_ALL_WIDTH);
				Dialog addBuddyDialog = new Dialog(
						Dialog.D_OK_CANCEL,
						BTalkLocale
								.getString(BTalkResource.BUDDY_SCREEN_POP_ADD_BUDDY_ID),
						0, null, Manager.USE_ALL_WIDTH);
				jidField = new EditField(EditField.NO_COMPLEX_INPUT
						| EditField.NO_NEWLINE);
				addBuddyDialog.add(jidField);
				addBuddyDialog
						.setDialogClosedListener(new DialogClosedListener() {
							public void dialogClosed(Dialog dialog, int choice) {
								switch (choice) {
								case 0:
									final String jid = jidField.getText();
									if (jid.indexOf('@') == -1) {
										Dialog.alert("Not a legal Email address!");
									} else {
										(new Thread() {
											public void run() {
												btalk.subscribe(jid);
											}
										}).start();
									}
									return;
								case -1:
									return;
								default:
									return;
								}
							}
						});
				addBuddyDialog.show();
			}

		});

		this.addMenuItem(new MenuItem(new StringProvider(BTalkLocale
				.getString(BTalkResource.BUDDY_SCREEN_MI_DELETE_BUDDY)),
				0x00020012, 0) {
			public void run() {
				// TODO finish delete buddy
				if (buddyList.buddyVector.size() <= 0)
					return;
				final Buddy b = buddyList.getBuddyAt(buddyList
						.getSelectedIndex());
				String str;
				if (!b.name.equals(b.jid))
					str = b.name + "(" + b.jid + ")";
				else
					str = b.jid;
				// int rst =
				// Dialog.ask(BTalkLocale.locale[BTalkLocale.ITEM_RM_LAB][SavedData.lang]+" \""+str+"\"?",
				// new String[] {"Yes", "No"}, new int[] {1, 2}, 2);
				int rst = Dialog.ask(
						BTalkLocale
								.getString(BTalkResource.BUDDY_SCREEN_POP_DELETE_BUDDY)
								+ " \"" + str + "\"?", new String[] { "Yes",
								"No" }, new int[] { 1, 2 }, 2);

				switch (rst) {
				case 1:
					(new Thread() {
						public void run() {
							btalk.unsubscribe(b.jid);
						}
					}).start();
					buddyList.deleteBuddy(b.jid);
					return;
				case 2:
					return;
				}
			}
		});

		this.addMenuItem(new MenuItem(new StringProvider(BTalkLocale
				.getString(BTalkResource.WHOLE_MI_OPTION)), 0x00030005, 0) {
			public void run() {
				btalk.pushScreen(new OptionScreen());
			}
		});

		this.addMenuItem(new MenuItem(new StringProvider(BTalkLocale
				.getString(BTalkResource.BUDDY_SCREEN_MI_EXIT)), 0x00030010, 0) {
			public void run() {
				btalk.exitBtalk();
			}
		});
		
		if (BTalk.DEBUG) {
			this.addMenuItem(new MenuItem(new StringProvider("Debug console"), 0x00030006, 0) {
				public void run() {
					btalk.pushScreen(BTalk.debugConsole);
				}
			});
		}

		this.addMenuItem(new MenuItem(new StringProvider(BTalkLocale
				.getString(BTalkResource.WHOLE_MI_CHECK_UPDATE)), 0x00030007, 0) {
			public void run() {
				(new UpdateChecker(btalk.use_wifi)).start();
			}
		});

		this.addMenuItem(new MenuItem(new StringProvider(BTalkLocale
				.getString(BTalkResource.WHOLE_MI_ABOUT)), 0x00030009, 0) {
			public void run() {
				Dialog.inform("hoodemia " + BTalk.VERSION
						+ "\nBy hoodemia\nhoodemia@gmail.com\n"
						+ BTalkLocale.getString(BTalkResource.ABOUT_MAIN_TEXT));
			}
		});
	}

	public boolean onClose() {
		if (btalk.state == BTalk.STATE_ONLINE
				|| btalk.state == BTalk.STATE_RETRYING
				|| btalk.state == BTalk.STATE_WAITING) {
			buddyList.replaceBuddies(allFriends);
			btalk.requestBackground();
		} else {
			btalk.exitBtalk();
		}
		return true;
	}

	public boolean pageDown(int amount, int status, int time) {
		return this.trackwheelRoll(amount, status, time);
	}

	public boolean pageUp(int amount, int status, int time) {
		return this.trackwheelRoll(amount, status, time);
	}
	
}
